package net.tngou.tnfs.action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.FileNameMap;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.ServletException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;


import org.apache.commons.lang3.reflect.FieldUtils;

import net.tngou.tnfs.pojo.Img;
import net.tngou.tnfs.util.HttpConfig;
import net.tngou.tnfs.util.ImgTool;

public class ImageAction extends BaseAction {

	/**
	 *   http://tnfs.tngou.net/image/news/150101/1.jpg_200x200[_oc|fc|tc]
	 *   oc:省略剪切
	 *   fc 填充剪切 
	 *   tc ：透明剪切
	 *   如果是   0x200 就指 高度为200宽度任意（等比例压缩）
	 *   如果是  200x0 就指  宽度为200高度度任意 （等比例压缩）
	 */
	@Override
	public void execute() throws ServletException, IOException {
		
		Img  img=_getImg();
		if(img.getWidth()<0||img.getHeight()<0) // 宽度限制
		{
			run_404();
			return;
		}
		HttpConfig httpConfig = HttpConfig.getInstance();
		if((img.getWidth()<httpConfig.getMinwidth()&&img.getWidth()!=0)||(img.getHeight()<httpConfig.getMinheight()&&img.getHeight()!=0)) //最小比例
		{
			    //最小宽度，高度限制 0x0除外	
				run_404();
				return;
			
		}
		if(img.getWidth()>httpConfig.getMaxwidth()||img.getHeight()>httpConfig.getMaxheight()) //最大比例
		{
			//最大宽度，高度限制
			run_404();
			return;
		}
		String rootPath = HttpConfig.getInstance().getTnfspath()+File.separator+"img";
		File imgfile = new File(rootPath+img.getSrc());
		if(!imgfile.isFile())
		{
			run_404();
			return;
		}
		String temp= HttpConfig.getInstance().getTnfspath()+File.separator+"temp"+File.separator+"image";
		File tempFile = new File(temp+img.getTemp()); 
		if(img.getWidth()>0&&img.getHeight()>0)
		{
			
			if(!tempFile.isFile())
			{
			   ImgTool imgTool = new ImgTool();
			   
			   BufferedImage bufferedImage = null;
			   switch (img.getCuttype()) {
				case "oc": //oc:省略剪切
					bufferedImage =imgTool.crop(imgTool.image(imgfile), img.getWidth(), img.getHeight());
					break;
				case "fc":// fc 填充剪切 
					bufferedImage = imgTool.crop(imgTool.image(imgfile), img.getWidth(), img.getHeight(),false);
					break;
				case "tc":// tc ：透明剪切
					bufferedImage = imgTool.crop(imgTool.image(imgfile), img.getWidth(), img.getHeight(),true);
					break;
				default:// 默认透明剪切
					bufferedImage = imgTool.crop(imgTool.image(imgfile), img.getWidth(), img.getHeight(),true);
					break;
				}
	   
			   if(!tempFile.getParentFile().isDirectory())
			   {
				   tempFile.getParentFile().mkdirs();
			   }
			   imgfile=imgTool.save(bufferedImage, tempFile);
			}else
			{
				imgfile=tempFile;
				
			}
		}
		else if(img.getWidth()*img.getHeight()==0&&(img.getWidth()>0||img.getHeight()>0)) //如果有一边 为 0 
		{
			if(!tempFile.isFile())
			{
				ImgTool imgTool = new ImgTool();
				BufferedImage bufferedImage = imgTool.resize(imgTool.image(imgfile), img.getWidth(), img.getHeight());
				if(!tempFile.getParentFile().isDirectory())
				   {
					   tempFile.getParentFile().mkdirs();
				   }
				   imgfile=imgTool.save(bufferedImage, tempFile);
			}
			else
			{
				imgfile=tempFile;
				
			}
		}
		else{
			
			
			
			
			if(!tempFile.isFile())
			{
				FileUtils.copyFile(imgfile, tempFile);
			}
		}
		
		
		
		printImg(imgfile);
		
		
	}
	
	
	
	
	protected void printImg(File file) throws IOException {
		
		 FileInputStream fis = new FileInputStream(file); 
		 int size =fis.available(); //得到文件大小   
	     byte data[]=new byte[size];   
	     fis.read(data);  //读数据   
	     fis.close();    
	    response.setContentType(_getMimeType(file)); //设置返回的文件类型   
	    OutputStream os = response.getOutputStream();  
	    os.write(data);  
	    os.flush();  
	    os.close(); 
	}
	
	
	private Img _getImg()
	{
		Img img = new Img();
		String path="";
		String action = request.getAction();
		if(StringUtils.isNoneEmpty(action)&&!"execute".equals(action))
			path=File.separator+action;
		String[] params = request.getParams();	
		for (String param : params) {
			path=path+File.separator+param;
		}
		img.setTemp(path);
		String[] paths = StringUtils.split(path, "_");
		
		String imgpath = paths[0];
		
		if(paths.length>1)
		{
			 String last = paths[paths.length-1];
			 String[] lasts = StringUtils.split(last, ".");
			 if(lasts.length>1)paths[paths.length-1]=lasts[0];
			 
		}
		
		img.setSrc(imgpath);
		img.setFormat(FilenameUtils.getExtension(imgpath));
		if(paths.length>1)
		{
			String st = paths[1];
			String[] sts = st.split("x");
			for (int i = 0; i < sts.length; i++) {
				if(i==0)
				{
					if(NumberUtils.isNumber(sts[i]))
					{
						img.setWidth(Integer.parseInt(sts[i]));
					}
				}
				else if(i==1)
				{
					if(NumberUtils.isNumber(sts[i]))
					{
						img.setHeight(Integer.parseInt(sts[i]));
					}
				}
				
			}
		}
		if(paths.length>2)
		{
			img.setCuttype(paths[2]);
		}
			
		return img;
		
	}
	
	
	private  String _getMimeType(File file)  
	{  		
			  FileNameMap fileNameMap = URLConnection.getFileNameMap();  
			   String type = fileNameMap.getContentTypeFor( file.getPath());  
		      return type;
	}  
		  
	
}
